from lib.config.index import sensor_config
from lib.sensors.lm35 import LM35
from lib.sensors.max98357 import Max98357
from machine import Pin
import time

lm35_config = sensor_config.get_sensor("LM35")
pin = lm35_config["pin"]
lm35 = LM35(pin)

max98357_config = sensor_config.get_sensor("MAX98357")
sck = max98357_config["sck"]
ws = max98357_config["ws"]
sd = max98357_config["sd"]
max98357 = Max98357(sck, ws, sd)

temp = -1

def read_lm35(keep = 1):
    global temp
    temp = round(lm35.read(), keep)
    if sensor_config.is_debug():
        print(f"{temp} C")
        time.sleep(0.2)
    return temp

def read_button():
    p = Pin(2, Pin.IN)
    v = p.value()
    if sensor_config.is_debug():
        print(v)
    return v == 0

def play():
    global temp
    pressed = read_button()
    if pressed:
        text = f"现在的温度是 {temp}摄氏度"
        max98357.network_play(text)
        time.sleep(2)


while True:
    read_lm35()
    if temp > 0:
        play()

